package com.ccsoft.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 演示 BIO 模型
public class Ch01BIOSocketServer {
    public static void main(String[] args) throws IOException {
        // 创建线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务端serverSocket开启了6666端口");

        while(true){// 死循环等待客户端连接
            // 有客户端连接到服务端则会执行下面一行代码，进而执行到下面的 print 语句
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            // 通过线程池创建线程，并执行指定的逻辑
            threadPool.execute(new Runnable() {
                public void run() {
                    handler(socket);
                }
            });
            // 上面代码定义了客户端、服务端通信的逻辑
            // 然后继续死循环等待其他客户端连接
        }
    }

    // 两者通信执行的逻辑
    public static void handler(Socket socket) {
        try{
            String threadInfo = "thread.id = " + Thread.currentThread().getId() + ",thread.name = " + Thread.currentThread().getName();
            System.out.println("开始处理 socket 消息，线程信息是：\n" + threadInfo);
            byte[] bytes = new byte[1024];
            // 获取 socket 的输入流
            InputStream inputStream = socket.getInputStream();

            // 循环读取数据
            while (true){
                int read = inputStream.read(bytes);
                if(read !=-1){
                    // 将客户端通过 socket 传输来的字节数组转换为字符串
                    String str = new String(bytes,0,read);
                    System.out.println(str);// 输出字符串
                }else{
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            System.out.println("开始关闭socket连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
